package com.action.mvc.sm.rabbit;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.ErrorHandler;

/**
 * 消费者
 */
@Component
public class MessageExecuteConsumer {

    @Autowired
    ConnectionFactory connectionFactory;
    @Autowired
    MessageExecuteConfig config;

    /**
     * 接受消息
     */
    @Bean
    public SimpleMessageListenerContainer messageExecuteContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueues(config.queueForMessageExecute());
        container.setExposeListenerChannel(true);
        container.setAcknowledgeMode(AcknowledgeMode.AUTO);
        container.setDefaultRequeueRejected(false);
        container.setErrorHandler(new ErrorHandler() {
            @Override
            public void handleError(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        });
        container.setMessageListener(new ChannelAwareMessageListener() {
            @Override
            public void onMessage(Message message, Channel channel) {
                try {
                    String messageBody = new String(message.getBody(), "UTF-8");
                    System.out.println("接受消息" + messageBody);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        });
        return container;
    }

}
